from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from home.models import NavModel
from home import models, homeser
from django.core.cache import cache


# Create your views here.
# 测试方法
class Topnav(APIView):
    def get(self, request):
        key = "topnav"
        cacheres = cache.get(key)
        if cacheres:
            return Response({"msg": "success", "data": cacheres, "code": 200})
        top = models.NavModel.objects.filter(position=True, isshow=True).order_by("order")
        ser = homeser.NavSerializer(top, many=True)
        cache.set(key, ser.data, 60 * 60 * 24)
        return Response({"msg": "success", "data": ser.data, "code": 200})


class Footnav(APIView):
    def get(self, request):
        # 设置一个缓存的key
        key = "footnav"
        # 判断缓存中是否存在这个key
        cacheres = cache.get(key)
        if cacheres:
            return Response({"msg": "success", "data": cacheres, "code": 200})
        top = models.NavModel.objects.filter(position=False, isshow=True).order_by("order")
        ser = homeser.NavSerializer(top, many=True)
        cache.set(key, ser.data, 60 * 60 * 24)
        return Response({"msg": "success", "data": ser.data, "code": 200})


# class BannerList(ListAPIView):
#     queryset = models.BannerModel.objects.filter(isshow=True).order_by("order")
#     serializer_class = homeser.BannerSerializer
class Banner(APIView):
    def get(self, request):
        banner = models.BannerModel.objects.filter(isshow=True).order_by("order")
        ser = homeser.BannerSerializer(banner, many=True)
        return Response({"msg": "success", "data": ser.data, "code": 200})


class BannerList(ListAPIView):
    queryset = models.BannerModel.objects.filter(isshow=True).order_by("order")
    serializer_class = homeser.BannerSerializer

    def list(self, request, *args, **kwargs):
        key = "bannernav"
        cacheres = cache.get(key)
        if cacheres:
            return Response({"msg": "success", "data": cacheres, "code": 200})
        queryset = self.get_queryset()
        ser = self.get_serializer(queryset, many=True)
        cache.set(key, ser.data, 60 * 60 * 24)
        return Response({"msg": "success", "data": ser.data, "code": 200})
